//
//  PhotoListViewController.swift
//  photoTool
//
//  Created by 刘清元 on 2022/8/27.
//

import UIKit
import Toast_Swift
import Photos
import WCDBSwift

enum ImgOrderType {
    case sizeLargeToSmall
    case sizeSmallToLarge
    case widthLargeToSmall
    case widthSmallToLarge
    case heightLargeToSmall
    case heightSmallToLarge
    case biliLargeToSmall
    case biliSmallToLarge
    case none
}

class PhotoListViewController: UIViewController, UIPopoverPresentationControllerDelegate {
    
    private let photoTool = PhotoSingle.shared
    private var listArr: [ImageModel] = [] {
        didSet {
            collectionView.listArr = [(title: "", list: listArr)]
        }
    }
    private var orderType: ImgOrderType = .none
    public var need_scan = false
    private var height = ""
    private var width = ""
    private var minSize = 0
    private var maxSize = 0
    // 是否是相册
    public var isAlbum = false
    public var albmModel = AlbumModel.init()
    private var value = UserDefaults.standard.value(forKey: "cellValue") as! Int
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if need_scan == true {
            if isAlbum == true {
                photoTool.scanImage(assetCollection: albmModel.collection!).scanComplete {
                    let alertView = UIAlertController.init(title: "提示", message: "扫描完成", preferredStyle: .alert)
                    let cancelAction = UIAlertAction.init(title: "确定", style: .cancel)
                    alertView.addAction(cancelAction)
                    self.present(alertView, animated: true)
                    self.getListData(album: self.albmModel.albumName)
                }
            }else{
                photoTool.registerPhoto().scanProgess {
                    self.view.makeToast("已扫描\(self.photoTool.didSave)")
                }
                .scanComplete {
                    let alertView = UIAlertController.init(title: "提示", message: "扫描完成", preferredStyle: .alert)
                    let cancelAction = UIAlertAction.init(title: "确定", style: .cancel)
                    alertView.addAction(cancelAction)
                    self.present(alertView, animated: true)
                    self.getListData(album: "")
                }
            }
        } else {
            getListData(album: isAlbum ? albmModel.albumName : "")
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .white
        let sizeSearchBtn = UIBarButtonItem.init(title: "大小", style: .plain, target: self, action: #selector(sizeSearchBtnClick))
        let searchBtn = UIBarButtonItem.init(title: "搜索", style: .plain, target: self, action: #selector(searchBtnClick))
        let orderBtn = UIBarButtonItem.init(title: "排序", style: .plain, target: self, action: #selector(orderBtnClick(barBtnItem:)))
        navigationItem.rightBarButtonItems = [orderBtn, searchBtn, sizeSearchBtn]
        
        let leftView = UIView.init()
        leftView.frame = CGRect(x: 0, y: 0, width: 340, height: 40)
        // 返回按钮
        let backBtn = UIButton.init(type: .custom)
        backBtn.setImage(UIImage.init(systemName: "chevron.left"), for: .normal)
        backBtn.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        leftView.addSubview(backBtn)
        backBtn.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
        // 调整大小
        if !ProcessInfo().isMacCatalystApp {
            let slider = UISlider.init()
            leftView.addSubview(slider)
            slider.value = 10
            slider.minimumValue = 10
            slider.maximumValue = 20
            //        slider.minimumValueImage = UIImage(systemName: "minus.circle")
            //        slider.maximumValueImage = UIImage(systemName: "plus.circle")
            slider.frame =  CGRectMake(40, 0, 300, 40)
            slider.addTarget(self, action: #selector(sliderValueChange(_:)), for: .valueChanged)
            navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftView)
            slider.isHidden = traitCollection.userInterfaceIdiom == .phone
        }
    }
    
    @objc func backBtnClick() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func sliderValueChange(_ slider:UISlider) {
        let sliderValue = slider.value
        let intValue = Int(sliderValue)
        if intValue != value {
            value = intValue
            UserDefaults.standard.setValue(value, forKey: "cellValue")
            collectionView.cellValue = value
            collectionView.reloadData()
        }
    }
    
    @objc func orderBtnClick(barBtnItem:UIBarButtonItem) {
        let titleArr = ["大小", "宽度", "高度","比例"]
        if traitCollection.userInterfaceIdiom == .phone{
            let alert = UIAlertController.init(title: "提示", message: "排序方式", preferredStyle: .actionSheet)
            for (index, item) in titleArr.enumerated() {
                let action = UIAlertAction.init(title: item, style: .default) { action1 in
                    self.orderAndSearch(index: index)
                }
                alert.addAction(action)
            }
            let cancelAction = UIAlertAction.init(title: "取消", style: .cancel)
            alert.addAction(cancelAction)
            present(alert, animated: true)
        }else{
            let VC = OrderByPopOverController.init()
            VC.preferredContentSize = CGSize(width: 100, height: 150)
            VC.modalPresentationStyle = .popover
            VC.popoverPresentationController?.delegate = self
            VC.popoverPresentationController?.barButtonItem = barBtnItem
            VC.popoverPresentationController?.permittedArrowDirections = .up
            VC.popoverPresentationController?.canOverlapSourceViewRect = false
            VC.mainTable.listArr = titleArr
            VC.mainTable.cellItemDidSelected { indexPath in
                VC.dismiss(animated: true)
                self.orderAndSearch(index: indexPath.row)
            }
            present(VC, animated: true)
        }
    }
    
    func orderAndSearch(index:Int){
        if index == 0 {
            if self.orderType == .sizeLargeToSmall {
                self.orderType = .sizeSmallToLarge
            } else {
                self.orderType = .sizeLargeToSmall
            }
        } else if index == 1 {
            if self.orderType == .widthLargeToSmall {
                self.orderType = .widthSmallToLarge
            } else {
                self.orderType = .widthLargeToSmall
            }
        } else if index == 2{
            if self.orderType == .heightLargeToSmall {
                self.orderType = .heightSmallToLarge
            } else {
                self.orderType = .heightLargeToSmall
            }
        }else{
            if self.orderType == .biliLargeToSmall {
                self.orderType = .biliSmallToLarge
            }else{
                self.orderType = .biliLargeToSmall
            }
        }
        self.getListData(album: self.isAlbum ? self.albmModel.albumName : "")
    }
    
    @objc func sizeSearchBtnClick() {
        let alert = UIAlertController.init(title: "提示", message: "输入文件大小", preferredStyle: .alert)
        let sureAction = UIAlertAction.init(title: "搜索", style: .default) { action in
            self.minSize = Int(alert.textFields!.first!.text!)!
            self.maxSize = Int(alert.textFields!.last!.text!)!
            self.getListData(album: self.isAlbum ? self.albmModel.albumName : "")
        }
        alert.addAction(sureAction)
        let cancelAction = UIAlertAction.init(title: "取消", style: .cancel)
        alert.addAction(cancelAction)
        alert.addTextField { textField in
            textField.placeholder = "最小值"
            textField.text = "\(self.minSize)"
            textField.keyboardType = .numberPad
        }
        alert.addTextField { textField in
            textField.placeholder = "最大值"
            textField.text = "\(self.maxSize)"
            textField.keyboardType = .numberPad
        }
        present(alert, animated: true)
    }
    
    @objc func searchBtnClick() {
        let alert = UIAlertController.init(title: "提示", message: "输入宽和高", preferredStyle: .alert)
        let sureAction = UIAlertAction.init(title: "搜索", style: .default) { action in
            self.width = alert.textFields?.first?.text ?? ""
            self.height = alert.textFields?.last?.text ?? ""
            self.getListData(album: self.isAlbum ? self.albmModel.albumName : "")
        }
        alert.addAction(sureAction)
        let cancelAction = UIAlertAction.init(title: "取消", style: .cancel)
        alert.addAction(cancelAction)
        alert.addTextField { textField in
            textField.placeholder = "宽"
            textField.keyboardType = .numberPad
        }
        alert.addTextField { textField in
            textField.placeholder = "高"
            textField.keyboardType = .numberPad
        }
        present(alert, animated: true)
    }
    
    func getListData(album:String) {
        var order:OrderBy = ImageModel.Properties.identifier.order(.ascending)
        var imageWhere:Condition = ImageModel.Properties.identifier >= 0
        if orderType != .none {
            switch orderType {
            case .sizeLargeToSmall:
                order = ImageModel.Properties.fileSize.order(.descending)
            case .sizeSmallToLarge:
                order = ImageModel.Properties.fileSize.order(.ascending)
            case .widthLargeToSmall:
                order = ImageModel.Properties.width.order(.descending)
            case .widthSmallToLarge:
                order = ImageModel.Properties.width.order(.ascending)
            case .heightLargeToSmall:
                order = ImageModel.Properties.height.order(.descending)
            case .heightSmallToLarge:
                order = ImageModel.Properties.height.order(.ascending)
            case .biliLargeToSmall:
                order = ImageModel.Properties.bili.order(.descending)
            case .biliSmallToLarge:
                order = ImageModel.Properties.bili.order(.ascending)
            case .none:
                order = ImageModel.Properties.identifier.order(.ascending)
            }
        }
        if !album.isEmpty {
            imageWhere = ImageModel.Properties.groupName == album && imageWhere
        }
        if !width.isEmpty {
            imageWhere = ImageModel.Properties.width <= width && imageWhere
        }
        if !height.isEmpty {
            imageWhere = ImageModel.Properties.height <= height && imageWhere
        }
        if minSize > 0 && maxSize > 0 {
            imageWhere = ImageModel.Properties.fileSize > minSize && ImageModel.Properties.fileSize < maxSize && imageWhere
        }
        listArr = try! FileTool().getDb().getObjects(fromTable: "image",where: imageWhere,orderBy: [order])
    }
    
    lazy var collectionView: ImageListCollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        let collect = ImageListCollectionView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH), collectionViewLayout: layout)
        view.addSubview(collect)
        collect.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        collect.cellItemDidSelected { indexPath in
            let model = self.listArr[indexPath.row]
            let alert = UIAlertController.init(title: "提示", message: "大小：\(model.fileSize!),宽：\(model.width!),高：\(model.height!)", preferredStyle: .alert)
            let sureAction = UIAlertAction.init(title: "删除", style: .default) { action in
                let localIdentifier = model.localIdentifier!
                PHPhotoLibrary.shared().performChanges {
                    let assetResult = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier], options: nil)
                    PHAssetChangeRequest.deleteAssets(assetResult)
                } completionHandler: { result, error in
                    if result == true{
                        DispatchQueue.main.async {
                            try! FileTool().getDb().delete(fromTable: "image",where: ImageModel.Properties.identifier == model.identifier!)
                            _ = FileTool().deleteFileWithPath(path: FileTool().getDocumentPath()+"/imageData/"+localIdentifier.md5)
                            // 删除相似表数据
                            try! FileTool().getDb().delete(fromTable: "repeated",where: RepeatedModel.Properties.rightImgId == localIdentifier || RepeatedModel.Properties.leftImgId == localIdentifier)
                            self.listArr.remove(at: indexPath.row)
                        }
                    }
                    print(error?.localizedDescription ?? "")
                }
            }
            alert.addAction(sureAction)
            let collectAction = UIAlertAction.init(title: "收藏", style: .default) { action in
                let localIdentifier = model.localIdentifier!
                PHPhotoLibrary.shared().performChanges {
                    let assetResult = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier], options: nil)
                    let request = PHAssetChangeRequest(for: assetResult[0])
                    request.isFavorite = !request.isFavorite
                }
            }
            alert.addAction(collectAction)
            let cancelAction = UIAlertAction.init(title: "取消", style: .cancel)
            alert.addAction(cancelAction)
            self.present(alert, animated: true)
        }
        return collect
    }()
    public func presentationControllerShouldDismiss(_ presentationController: UIPresentationController) -> Bool {
        return true
    }
    //必须设置为none,否则没有弹窗效果
    public func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return .none
    }
}
